// Copyright (c) 2022, hzmes and contributors
// For license information, please see license.txt

frappe.ui.form.on('SRM Sample Request', {

	refresh: function(frm) {
		frm.set_df_property("approval", "description", frm.doc.approval_name);
		// 2023-03-30: JS实现下推生成[样品承认单],前提条件: 是否执行 + 待收料 + 采购员角色
		if (!frm.is_new() && frm.doc.if_execute == 1 && (frm.doc.workflow_state == 'Be Received' || frm.doc.workflow_state == 'Finish') && frappe.user.has_role('SRM Purchase'))
		frm.add_custom_button(__('下推承认单'), () => {
			frappe.db.get_list('SRM Sample Admit', {fields: ['name'],filters: {rcbillno: frm.doc.name}})
					.then(records => {	
						if (records.length == 0) {
							// 纯JS的New Doc
							let new_doc = frappe.model.get_new_doc("SRM Sample Admit");
							new_doc.rcbillno = frm.doc.name;
							frappe.set_route("Form", new_doc.doctype, new_doc.name);
						}
						else if (records.length > 0) {frappe.msgprint(`已经在承认中, 承认单号链接: <a href = http://umsrm.unionman.net:8070/app/srm-sample-admit/${records[0].name}>${records[0].name}</a>`)}
					})
		});
		// 给供应商列表中的邮箱发送邮件
		if (frm.doc.if_execute == 1 && (frm.doc.workflow_state == 'Be Received' || frm.doc.workflow_state == 'Hand In')) {
			frm.add_custom_button("发送邮件", () => {
				if (frm.doc.supplier_subs) {
					if (frm.doc.admit_closed == 1) {
						frappe.confirm('已经发送, 需要重新发送一次?',
							() => {
								// action to perform if Yes is selected
								// 链式操作:先把当前子表中的email遍历(如果某一行有多个email地址并且是用,号分隔的)出来；再toString()组合为字符串;再转换为列表
								var rev_emails = cur_frm.doc.supplier_subs.map((item) =>{return item.email.split(',')}).toString().split(",")
								if (rev_emails) {
									frm.call({
										method: "send_supplier_emails",
										doc: frm.doc,
										args: {
											rev_email: rev_emails,
											// rev_email: ['644480509@qq.com'],
										},
										freeze: true,
										freeze_message: __("running..."),
										callback: function(r) {
											frappe.msgprint("已经安排邮件发送队列!");
										}
									})
								}
							}, () => {
								// action to perform if No is selected
							})
					}
					else {
						// 链式操作:先把当前子表中的email遍历(如果某一行有多个email地址并且是用,号分隔的)出来；再toString()组合为字符串;再转换为列表
						var rev_emails = cur_frm.doc.supplier_subs.map((item) =>{return item.email.split(',')}).toString().split(",")
						if (rev_emails) {
							frm.call({
								method: "send_supplier_emails",
								doc: frm.doc,
								args: {
									rev_email: rev_emails,
								},
								freeze: true,
								freeze_message: __("running..."),
								callback: function(r) {
									frappe.msgprint("已经安排邮件发送队列!");
								}
							})
						}
					}
				}
				else {
					frappe.msgprint("供应商收件人不能为空!")
				}
			})
		};
		// 增加确认回样操作
		if (frm.doc.workflow_state == 'Be Received') {
			frm.add_custom_button("采购回复交期", () => {
				// 如果已经有回样日期只做事后修改
				var names = [''];//先有个''
				cur_frm.doc.supplier_subs.forEach((i)=>{names.push(i.supplier_name)});//从子表中循环push
				var set_tmp = new Set(names);//转为set去重
				var supplier_names = Array.from(set_tmp);//set转list
				
				if (frm.doc.answer_date_from_purchase) {
					frappe.prompt([{
						label: '供应商',
						fieldname: 'supplier_select',
						fieldtype: 'Select',
						options: supplier_names,
						// 只有一个供应商则默认携带, 如果有多个则手工选择
						default: () => { return supplier_names.length > 2 ? '' : supplier_names[1] }
					},
					{
						label: '回样日期',
						fieldname: 'date',
						fieldtype: 'Date'
					}], (values) => {
						// console.log(values.date);
						frm.set_value('answer_date_from_purchase', values.date);
						frm.set_value('curren_supplier', values.supplier_select);
						frm.refresh_field(['answer_date_from_purchase', 'curren_supplier']);
						frm.save();
					})
				}
				// 第一次设置时同时记录时间,以计算是否超期
				else {
					frappe.prompt([{
						label: '供应商',
						fieldname: 'supplier_select',
						fieldtype: 'Select',
						options: supplier_names,
						default: () => { return supplier_names.length > 2 ? '' : supplier_names[1] }
					},
					{
						label: '回样日期',
						fieldname: 'date',
						fieldtype: 'Date'
					}], (values) => {
						// console.log(values.date);
						frm.set_value('answer_date_from_purchase', values.date);
						frm.set_value('curren_supplier', values.supplier_select);
						frm.set_value('confirm_return_date', frappe.datetime.get_today());
						frm.refresh_field(['answer_date_from_purchase', 'confirm_return_date']);
						frm.save();
					})
				}
			})
		};
		// 增加实际回样操作
		if (frm.doc.workflow_state === "Be Received" && frappe.user.has_role('SRM Dev Manager')) {
			frm.add_custom_button("实际回样", () => {
				if (1 == 1) {
					frappe.prompt({
						label: '实际回样数量',
						fieldname: 'real_receive_qty',
						fieldtype: 'Float'
					}, (values) => {
						console.log(values.real_receive_qty);
						frappe.call({
							method: "field_update",
							doc: cur_frm.doc,
							args: { "dict" : { "real_receive_qty" : values.real_receive_qty, "real_receive_date" : frappe.datetime.get_today() } },
						});
					})
				}
				frm.refresh_field('real_receive_qty');
				frm.refresh_field('real_receive_date');
			})
		};
		// 增加[特殊维护]:实际场景就是交期延误的事后说明、解释
		// 2023-02-08取消了条件:frm.doc.workflow_state === "Be Received" && ，在任何状态下按钮可见可操作
		if (frappe.user.has_role('SRM Purchase')) {
			frm.add_custom_button("特殊维护", () => {
				if (1 == 1) {
					frappe.prompt({
						label: '交期延误特别说明',
						fieldname: 'note_of_delay',
						fieldtype: 'Small Text'
					}, (values) => {
						// frappe.show_alert({
						// 	message:__(`${values.note_of_delay}特殊维护成功!`),
						// 	indicator:'green'
						// }, 5);
						frappe.call({
							method: "field_update",
							doc: cur_frm.doc,
							args: { "dict" : { "note_of_delay" : values.note_of_delay } },
							callback: function(r) {
								frappe.show_alert({
									message:__('特殊维护成功!'),
									indicator:'green'
								}, 5);
							}
						});
					})
				}
				// frm.refresh_field('note_of_delay');
				// frm.save();
			})
		};
	},

	setup: function(frm) {
		
		// 限制供应商的下拉选项
		frm.set_query('supplier', 'supplier_subs', function(doc, cdt, cdn) {
			const rorw = locals[cdt][cdn];
			return {
				'filters': { managestatus: ['in', ['四级', '二级', '三级']] }
			}
		});
		// 限制下拉选项
		frm.set_query('material_company', function(doc) {
			return {
				'filters': { 'group': '内部供应商'}
			}
		});
		
		// 配置默认值为GYN0001，即广东九联公司
		if (!frm.doc.material_company) {
			frm.set_value("material_company", "GYN0001");
		}
	},

	
	before_workflow_action: (frm) => {
        // console.log(frm.selected_workflow_action);
		// 提交
        if (frm.doc.workflow_state === "Save" && frm.selected_workflow_action === "Approve") {
			frappe.call({
				method: "field_update",
				doc: cur_frm.doc,
				args: { "dict": { "approval" : frappe.session.user, "approval_date" : frappe.datetime.get_today() } },
				callback: function(r) {
					frappe.show_alert({
						message:__('Approve Success!'),
						indicator:'green'
					}, 5);
				}
			});
        };
		// 判定
		if (frm.doc.workflow_state === "Hand In" && frm.selected_workflow_action === "Determine") {
            frappe.call({
				method: "field_update",
				doc: cur_frm.doc,
				args: { "dict": {"purchaser": frappe.session.user} },
				callback: function(r) {
					// 判定后自动发送邮件
					var rev_emails = cur_frm.doc.supplier_subs.map((item) =>{return item.email.split(',')}).toString().split(",")
					if (rev_emails) {
						frm.call({
							method: "send_supplier_emails",
							doc: frm.doc,
							args: {
								rev_email: rev_emails,
							},
							freeze: true,
							freeze_message: __("安排邮件发送队列..."),
							callback: function(r) {
								frappe.show_alert({
									message:__('成功安排邮件发送队列!'),
									indicator:'green'
								}, 10);
							}
						})
					};
				}
			});
        };
		// 收回判定
		if (frm.doc.workflow_state === "Be Received" && frm.selected_workflow_action === "Determine Back Step") {
            frappe.call({
				method: "field_update",
				doc: cur_frm.doc,
				args: { "dict": { "purchaser" : "", "purchaser_name": ""} },
				callback: function(r) {
					frappe.show_alert({
						message:__('Determine Back Ste Success!'),
						indicator:'green'
					}, 5);
				}
			});
        };
    },

	// 任务类型必选其一
	before_save: function(frm) {
		if (frm.doc.return_date == undefined) {
			console.log(frm.doc.requirement_date)
			frm.set_value("return_date", frappe.datetime.add_days(frm.doc.requirement_date, -1))
			frm.refresh_field("return_date")
		}
		let is_allowed = frm.doc.is_prototype || frm.doc.is_trial_production || frm.doc.is_order_support || frm.doc.is_service || frm.doc.is_manufacturing || frm.doc.is_other_note;
		// console.log(is_allowed)
		if (!is_allowed) { frappe.throw("任务类型必选其一!") }
	},
	
	sample_category_dev: function(frm) {
		// 默认携带
		frm.set_value('sample_category_purchase', frm.doc.sample_category_dev);
		// 根据当前的sample_category_dev去获取standard_lead_time
		frappe.db.get_doc('SRM Material Group', cur_frm.doc.sample_category_dev)
			.then((r) => {
				if (r) {
					var reply_date = frappe.datetime.add_days(frappe.datetime.get_today(), r.standard_lead_time)
					frm.set_value('reply_date', reply_date)
					frm.refresh_field('reply_date')
				}
			})
	},

	requirement_date: function(frm) {
		// 利用标准的frappe.datetime.add_days方法
		var return_date = frappe.datetime.add_days(frm.doc.requirement_date, -1)
		frm.set_value('return_date', return_date)
		frm.refresh_field('return_date')
	},

	// 默认携带
	element_qty_1: function(frm) {
		frm.set_value('element_qty_2', frm.doc.element_qty_1);
	},

});

frappe.ui.form.on('SRM Sample Request Sub', {
	// refresh: function(frm) {

	// }

	supplier: function(frm, cdt, cdn) {
		let row = locals[cdt][cdn];
		let email_get = '';
		let r = frappe.db.get_list('SRM Supplier Contact Sub',
                   {filters:{'parent': row.supplier}, fields:['email_address'], as_list:true}
			).then( (r) => {
				if (r) {
					email_get = r.join(",");
					// console.log(r);
				}
			}).then ( () => {
				// console.log(b + '-' + email_get);
				row.email = email_get;
				frm.refresh_field('supplier_subs');
			})
	}
});


// 获取当日流水号Series:连续调用frappe.db.get_value和frappe.db.set_value
// SRM Naming Series必须授与权限给All角色 20221017
// frappe.db.get_value('SRM Naming Series', 
// 					{'doctype_name': cur_frm.doctype, 'date': frappe.datetime.get_today()}, 
// 					['name', 'current_series']
// 					).then((r)=>{
// 						// 返回后赋值get_series
// 						// get_series = r.message.current_series;
// 						// 获取当前日期后进行格式化转换:去掉-再拼接
// 						frm.doc.naming_series = 'YPSQ-';
// 						frm.doc.naming_series += frappe.datetime.get_today().split('-').join('');
// 						// 在r.message.current_series基础上以0自动补位:数字+''相当于是转换为字符串
// 						frm.doc.naming_series += (r.message.current_series + '').padStart(3,'0');
// 						// frm.doc.naming_series += get_series.toString();
// 						// 获取后马上更新记录表中的当前流水号
// 						frappe.db.set_value('SRM Naming Series', 
// 											r.message.name, 
// 											'current_series', 
// 											r.message.current_series + 1
// 											);
// 						})